package util;

import java.io.*;

public class CopyFile {
    // 测试
    public static void main(String[] args) {
        try {
            copyDir("D:\\天翼云盘下载", "E:\\电子书\\极客时间");
            System.out.print("复制成功");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.print("复制失败");
        }
    }

    // 复制文件
    public static void copyFile(File source, File target) throws IOException {
        FileInputStream input = new FileInputStream(source);
        FileOutputStream out = new FileOutputStream(target);
        BufferedOutputStream outbuff = new BufferedOutputStream(out);

        byte[] b = new byte[1024];
        int len = 0;
        while ((len = input.read(b)) != -1) {
            outbuff.write(b, 0, len);
        }

        outbuff.close();
        out.close();
        input.close();
    }

    // 复制文件夹
    public static void copyDir(String source, String target) throws IOException {
        new File(target).mkdirs();
        File[] files = new File(source).listFiles();
        for (File file:files) {
            String fileName = file.getName();
            System.out.println(fileName.substring(fileName.lastIndexOf(".") + 1));
            if (file.isFile() && fileName.substring(fileName.lastIndexOf(".") + 1).equals("html")) {
                File targetFile = new File(target + File.separator + file.getName());
                copyFile(file, targetFile);
            } else if (file.isDirectory()) {
                String sour = source + File.separator + file.getName();
                String tar = target + File.separator + file.getName();
                copyDir(sour, tar);
            }
        }
    }
}
